package com.huntmobi.springsecuritydemo.base.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.huntmobi.springsecuritydemo.base.enums.ContextTypeEnum;
import com.huntmobi.springsecuritydemo.base.enums.HttpEnum;
import com.huntmobi.springsecuritydemo.base.http.Request;
import com.huntmobi.springsecuritydemo.base.http.Response;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * <p>
 *
 * @Author：zouzhimin
 * @description：登录失败处理，json返回
 * @date：crealed in 11:45 2020/7/7
 * </P>
 **/
@Component
public class JsonAuthenticationFailureHandler implements AuthenticationFailureHandler {

    @Override
    public void onAuthenticationFailure(HttpServletRequest req, HttpServletResponse resp, AuthenticationException e) throws IOException, ServletException {
        resp.setContentType(ContextTypeEnum.JSONUTF8.getContextType());
        PrintWriter out = resp.getWriter();
        Request result = Response.error(HttpEnum.LOGINFAIL.getCode(),HttpEnum.LOGINFAIL.getMsg());
        out.write(new ObjectMapper().writeValueAsString(result));
        out.flush();
        out.close();
    }

}
